﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using AEM.Common;
using AEM.Data;
using AEM.Data.Enum;

namespace AEM.Controls
{
    /// <summary>
    /// HallCallRatio.xaml 的交互逻辑
    /// </summary>
    public partial class HallCallRatio : UserControl
    {
        public HallCallRatio()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(WaitingRatio_Loaded);
            this.btn_select.Click += new RoutedEventHandler(btn_select_Click);
            this.datefrom.ValueChanged += new EventHandler(datefrom_SelectedDateChanged);
            this.dateto.ValueChanged += new EventHandler(dateto_SelectedDateChanged);
            this.listHallCallRatio.SelectionChanged += new SelectionChangedEventHandler(listWaitingRatio_SelectionChanged);
            this.btn_reset.Click += new RoutedEventHandler(btn_reset_Click);
            this.liftNum.SelectionChanged += new SelectionChangedEventHandler(liftNum_SelectionChanged);
        }

        void liftNum_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Data.Model.LiftInfo r = (Data.Model.LiftInfo)this.liftNum.SelectedItem;
            if (null == r) return;
            this.liftLandings.Visibility = Visibility.Visible;

            List<KeyValuePair<string, int>> flist = new List<KeyValuePair<string, int>>();
            string[] floors = r.LiftActualFloor.Split(',');
            int len = floors.Length;
            for (int i = 1; i <= len; i++)
            {
                flist.Add(new KeyValuePair<string, int>(floors[i - 1], i));
            }
            this.liftLandings.ItemsSource = flist;
            this.liftLandings.Items.Refresh();
        }

        void btn_reset_Click(object sender, RoutedEventArgs e)
        {
            this.liftLandings.Visibility = Visibility.Collapsed;
            //this.liftNum.SelectedItem = null;
            this.liftNum.SelectedIndex = 0;
            this.liftDirection.SelectedItem = null;
            this.liftLandings.SelectedItem = null;
            this.datefrom.Value = DateTime.Now;
            this.dateto.Value = DateTime.Now;
        }

        void WaitingRatio_Loaded(object sender, RoutedEventArgs e)
        {
            if (null != Config.LiftInftList)
                this.liftNum.ItemsSource = from r in Config.LiftInftList
                                           where r.LiftType == (int)LiftType.电梯
                                           select r;
            this.liftNum.Items.Refresh();
            this.liftNum.SelectedIndex = 0;
            DateTime s = DataLogHelper.GetEarliestTime();
            if (null != s)
            {
                this.datefrom.DisplayDateStart = s;
                this.dateto.DisplayDateStart = s;
            }
            else
            {
                this.datefrom.DisplayDateStart = DateTime.Now;
            }
            this.datefrom.DisplayDateEnd = DateTime.Now;
            this.dateto.DisplayDateEnd = DateTime.Now;

            List<KeyValuePair<string, int>> dlist = new List<KeyValuePair<string, int>>();
            dlist.Add(new KeyValuePair<string, int>(this.TryFindResource("UpCall") as string, (int)CallType.Up));
            dlist.Add(new KeyValuePair<string, int>(this.TryFindResource("DownCall") as string, (int)CallType.Down));
            this.liftDirection.ItemsSource = dlist;
            this.liftDirection.Items.Refresh();
            //if (null != Config.LiftInftList)
            //{
            //    var f = (from r in Config.LiftInftList
            //             where r.LiftType == (int)LiftType.电梯
            //             select r.LiftActualFloor).Max();
            //    if (null == f) return;

            //    List<KeyValuePair<string, int>> flist = new List<KeyValuePair<string, int>>();
            //    int len = f.Split(',').Length;
            //    for (int i = 1; i <= len; i++)
            //    {
            //        flist.Add(new KeyValuePair<string, int>(i.ToString(), i));
            //    }
            //    this.liftLandings.ItemsSource = flist;
            //    this.liftLandings.Items.Refresh();
            //}
            ResetSeries();

            this.waitingSeries.Title = this.TryFindResource("CountUnit") as string;
        }

        private void ResetSeries()
        {
            List<KeyValuePair<string, int>> valueList = new List<KeyValuePair<string, int>>();
            valueList.Add(new KeyValuePair<string, int>(this.TryFindResource("ShortName") as string, 0));
            this.waitingRatio.DataContext = valueList;
        }

        void dateto_SelectedDateChanged(object sender, EventArgs e)
        {
            this.datefrom.DisplayDateEnd = this.dateto.Value;
        }

        void datefrom_SelectedDateChanged(object sender, EventArgs e)
        {
            this.dateto.DisplayDateStart = this.datefrom.Value;
        }

        void btn_select_Click(object sender, RoutedEventArgs e)
        {
            this.btn_reset.IsEnabled = false;
            ResetSeries();
            this.msg.Text = "";
            if (null == this.datefrom.Value)
            {
                this.msg.Text = string.Format(this.TryFindResource("AskSelectOne") as string, this.TryFindResource("DateFrom") as string);
                this.btn_reset.IsEnabled = true; return;
            }
            if (null == this.dateto.Value)
            {
                this.msg.Text = string.Format(this.TryFindResource("AskSelectOne") as string, this.TryFindResource("DateTo") as string);
                this.btn_reset.IsEnabled = true; return;
            }
            DateTime s = this.datefrom.Value.Value;
            DateTime t = this.dateto.Value.Value;
            int d = -1;
            int l = -1;
            if (null != this.liftDirection.SelectedValue)
                d = (int)this.liftDirection.SelectedValue;
            if (null != this.liftLandings.SelectedValue)
                l = (int)this.liftLandings.SelectedValue;

            this.msg.Text = this.TryFindResource("Searching") as string;
            if (null != this.liftNum.SelectedItem)
            {
                Data.Model.LiftInfo r = (Data.Model.LiftInfo)this.liftNum.SelectedItem;
                CreateGridView(r.LiftActualFloor.Split(','));

                CreateData(r, s, t, d, l);
            }
            else
            {
                if (null == Config.LiftInftList) { this.listHallCallRatio.ItemsSource = null; return; }
                var f = (from Data.Model.LiftInfo r in Config.LiftInftList
                         where r.LiftType == (int)LiftType.电梯
                         select r.LiftActualFloor).Max();
                int len = f.Split(',').Length;
                CreateGridView(len);

                CreateData(null, s, t, d, l);
            }

            this.listHallCallRatio.Items.Refresh();
            this.listHallCallRatio.SelectedIndex = 0;
            this.btn_reset.IsEnabled = true;
            this.msg.Text = this.TryFindResource("SearchOK") as string;
        }

        private void CreateData(Data.Model.LiftInfo r, DateTime s, DateTime t, int d, int l)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("ShortName", typeof(string)));
            if (null != r)
            {
                if (-1 != l)
                {
                    dt.Columns.Add(new DataColumn(r.LiftActualFloor.Split(',')[l - 1], typeof(int)));
                }
                else
                {
                    string[] floors = r.LiftActualFloor.Split(',');
                    for (int i = 0; i < floors.Length; i++)
                    {
                        dt.Columns.Add(new DataColumn(floors[i], typeof(int)));
                    }
                }
                dt.Rows.Add(CreateItem(r, s, t, d, l, dt));
            }
            else
            {
                var f = (from Data.Model.LiftInfo row in Config.LiftInftList
                         where row.LiftType == (int)LiftType.电梯
                         select row.LiftActualFloor).Max();
                string[] floors = f.Split(',');
                for (int i = 0; i < floors.Length; i++)
                {
                    dt.Columns.Add(new DataColumn(floors[i], typeof(int)));
                }
                foreach (Data.Model.LiftInfo row in Config.LiftInftList)
                {
                    if (null != row)
                        dt.Rows.Add(CreateItem(row, s, t, d, l, dt));
                }
            }
            this.listHallCallRatio.ItemsSource = dt.DefaultView;
        }

        void listWaitingRatio_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView v = (DataRowView)this.listHallCallRatio.SelectedItem;
            if (null != v)
                RefreshSeries(v.Row);
        }

        void RefreshSeries(DataRow rd)
        {
            if (null == rd) return;
            List<KeyValuePair<string, int>> valueList = new List<KeyValuePair<string, int>>();

            for (int i = 1; i < rd.Table.Columns.Count; i++)
            {
                valueList.Add(new KeyValuePair<string, int>(rd.Table.Columns[i].ColumnName, Convert.ToInt32(rd[i])));
            }
            this.waitingRatio.DataContext = valueList;

            this.waitingRatio.LegendTitle = rd["ShortName"].ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="r">电梯</param>
        /// <param name="s">开始时间</param>
        /// <param name="t">结束时间</param>
        /// <param name="d">上下行</param>
        /// <param name="l">层站</param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DataRow CreateItem(Data.Model.LiftInfo r, DateTime s, DateTime t, int d, int l, DataTable dt)
        {
            try
            {
                if (-1 != l)
                {
                    int count = 0;
                    count = DataLogHelper.GetHallCallCount(r, s, t, d, l);
                    DataRow nw = dt.NewRow();
                    for (int i = 1; i < dt.Columns.Count; i++) nw[i] = 0;
                    nw[0] = r.ShortName;
                    nw[r.LiftActualFloor.Split(',')[l - 1]] = count;
                    return nw;
                }
                else
                {
                    string[] floors = r.LiftActualFloor.Split(',');
                    int len = floors.Length;
                    DataRow nw = dt.NewRow();
                    for (int i = 1; i < dt.Columns.Count; i++) nw[i] = 0;
                    nw[0] = r.ShortName;
                    int[] nc = DataLogHelper.GetHallCallCount(r, s, t, d);

                    for (int i = 0; i < (len > nc.Length ? nc.Length : len); i++)
                    {
                        nw[floors[i]] = nc[i];
                    }
                    return nw;
                }
            }
            catch
            {
                return null;
            }
        }

        private void CreateGridView(int len)
        {
            GridView g = new GridView();
            GridViewColumn sn = new GridViewColumn();
            sn.Header = (string)this.TryFindResource("ShortName");
            sn.DisplayMemberBinding = new Binding("ShortName");
            g.Columns.Add(sn);

            for (int i = 1; i <= len; i++)
            {
                GridViewColumn f = new GridViewColumn();
                f.Header = "F" + i;
                f.DisplayMemberBinding = new Binding("F" + i);
                g.Columns.Add(f);
            }
            this.listHallCallRatio.View = g;
        }

        private void CreateGridView(string[] floors)
        {
            GridView g = new GridView();
            GridViewColumn sn = new GridViewColumn();
            sn.Header = (string)this.TryFindResource("ShortName");
            sn.DisplayMemberBinding = new Binding("ShortName");
            g.Columns.Add(sn);

            for (int i = 0; i < floors.Length; i++)
            {
                GridViewColumn f = new GridViewColumn();
                f.Header = floors[i];
                f.DisplayMemberBinding = new Binding(floors[i]);
                g.Columns.Add(f);
            }
            this.listHallCallRatio.View = g;
        }
    }
}
